package com.xxx.springboot.util;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * Jasypt加解密工具类
 */
public class JasyptUtil {

	/**
	 * jasypt加密
	 * 
	 * @param password
	 *            配置文件中设定的密码（类似MD5的salt）
	 * @param message
	 *            要加密的明文
	 * @return
	 */
	public static String encyptPwd(String password, String message) {
		PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
		encryptor.setConfig(config(password));
		String result = encryptor.encrypt(message);
		return result;
	}

	/**
	 * jasypt解密
	 * 
	 * @param password
	 *            配置文件中设定的密码（类似MD5的salt）
	 * @param secretMessage
	 *            要解密的密文
	 * @return
	 */
	public static String decyptPwd(String password, String secretMessage) {
		PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
		encryptor.setConfig(config(password));
		String result = encryptor.decrypt(secretMessage);
		return result;
	}

	/**
	 * jasypt config
	 * @param password
	 *            配置文件中设定的加密salt
	 * @return
	 */
	public static SimpleStringPBEConfig config(String password) {
		SimpleStringPBEConfig config = new SimpleStringPBEConfig();
		config.setPassword(password);
		config.setAlgorithm("PBEWithMD5AndDES"); // 默认的加密方式，还可以是PBEWithMD5AndTripleDES
		config.setKeyObtentionIterations("1000");
		config.setPoolSize("1");
		config.setProviderName("SunJCE");
		config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
		config.setStringOutputType("base64");
		return config;
	}

	public static void main(String[] args) {
		String password = "test123abc";
		String message = "123456";
		String secretMessage = "";
		System.out.println("message:"+message);

		// jasypt加密
//		secretMessage = encyptPwd(password, message);
//		System.out.println("secretMessage:"+secretMessage);

		// jasypt解密
		// 正确的密文
		String rightSecretMessage = "u1VCGSNhzr+wu+GuVM0wOA==";
		System.out.println("decyptMessage:" + decyptPwd(password, rightSecretMessage));

		// 错误的密文：抛出异常
//		String wrongSecretMessage = "3tcQnKOfcdzzwYrvTwhuFw==";
//		System.out.println("decyptMessage:" + decyptPwd(password, wrongSecretMessage));

		// jasypt加密（多次执行，生成的密文是不同的）
		for (int i=0; i<10; i++) {
			secretMessage = encyptPwd(password, message);
			System.out.println("secretMessage"+ i + ":" + secretMessage);
		}

	}
}
